package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;
//     * 文件上传的步骤:
//     *     1.判断bucket是否存在
//     *         存在: 执行文件上传的逻辑
//     *         不存在: 创建bucket ,添加策略
//     *     2.防止文件重名
//     *         uuid
//     *         uuid+文件名.jpg
//     *         分目录存储
//     *     3.链接minio实现文件上传,IO流的方式传递
//     *     4.封装返回的url的地址
@Override
public String upload(MultipartFile file) {
    try {
        //检查bucket是否创建
        createBucket();

        //2.准备文件上传的路径
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String uuidName = UUID.randomUUID().toString() +"-"+file.getOriginalFilename();
        String path = datePath + uuidName;

        //3.实现文件上传
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(path)
                .contentType(file.getContentType())
                .stream(file.getInputStream(), file.getSize(),-1).build();
        minioClient.putObject(putObjectArgs);

        //4.拼接路径动态返回
        String url = minioProperties.getEndpoint() +"/" + minioProperties.getBucketName() + path;
        return url;
    }catch (Exception e){
        //将程序都转化为运行时异常
        e.printStackTrace();
        //需求:想返回自定义的异常  枚举类型
        //throw new RuntimeException(e);

        throw new LeaseException(ResultCodeEnum.SERVICE_ERROR);
    }
}

    public void createBucket() throws Exception {

        //1.判断bucket是否存在
        BucketExistsArgs bucketExistsArgs =
                BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build();
        boolean flag = minioClient.bucketExists(bucketExistsArgs);

        //2.判断是否创建
        if(!flag){
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder()
                    .bucket(minioProperties.getBucketName()).build();
            minioClient.makeBucket(makeBucketArgs);

            //3.设置配置策略
            SetBucketPolicyArgs setBucketPolicyArgs =
                    SetBucketPolicyArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .config(getConfig()).build();
            minioClient.setBucketPolicy(setBucketPolicyArgs);



        }
    }

    public String getConfig(){
        return
                """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
            """.formatted(minioProperties.getBucketName());
    }
}

